package com.besall.allbase.view.activity.log;

import static com.besall.allbase.common.Constants.KEY_STOP_WATCH_LOG;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidx.appcompat.widget.SwitchCompat;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.devicelist.XZDeviceListActivity;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.Log;
import bb.lanxing.view.dialog.CircularProgressDialog;
import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.service.base.BBServiceListener;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.message.Constants;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.common.utils.PreferenceUtil;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.IProtocolActivity;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;
import com.besall.allbase.view.base.BaseActivity;
import com.blankj.utilcode.util.ToastUtils;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class StopWatchLogActivity extends BaseActivity<IProtocolActivity, ProtocolPresenter> implements BesServiceListener, BBServiceListener {
	private CircularProgressDialog mCircularProgressDialog;

	private final List<RadioButton> mRadioButtonList = new ArrayList<>();

	@Override protected ProtocolPresenter createPresenter() {
		return ProtocolPresenter.getInstance();
	}

	@Override protected void initBeforeSetContent() {

	}

	@Override protected int getContentViewId() {
		return R.layout.activity_stop_watch_log;
	}

	@Override protected void bindView() {
		getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
	}

	@Override protected void initView() {
		RadioButton radioButton1 = findViewById(R.id.radioButton1);
		RadioButton radioButton2 = findViewById(R.id.radioButton2);
		RadioButton radioButton3 = findViewById(R.id.radioButton3);
		RadioButton radioButton4 = findViewById(R.id.radioButton4);
		RadioButton radioButton5 = findViewById(R.id.radioButton5);
		RadioButton radioButton6 = findViewById(R.id.radioButton6);
		RadioButton radioButton7 = findViewById(R.id.radioButton7);

		radioButton1.setTag(1);
		radioButton2.setTag(2);
		radioButton3.setTag(3);
		radioButton4.setTag(4);
		radioButton5.setTag(5);
		radioButton6.setTag(6);
		radioButton7.setTag(7);

		mRadioButtonList.add(radioButton1);
		mRadioButtonList.add(radioButton2);
		mRadioButtonList.add(radioButton3);
		mRadioButtonList.add(radioButton4);
		mRadioButtonList.add(radioButton5);
		mRadioButtonList.add(radioButton6);
		mRadioButtonList.add(radioButton7);

		ImageView back = findViewById(R.id.img_back);
		back.setOnClickListener(v -> finish());

		SwitchCompat switchCompat = findViewById(R.id.switch_log);
		boolean isOpen = (boolean) PreferenceUtil.get(StopWatchLogActivity.this, KEY_STOP_WATCH_LOG, false);
		switchCompat.setChecked(isOpen);
		if (isOpen) {
			switchCompat.setText(R.string.setting_stop_watch_log_off);
		} else {
			switchCompat.setText(R.string.setting_stop_watch_log_on);
		}

		RadioGroup radioGroup = findViewById(R.id.radioGroup);
		Button submitButton = findViewById(R.id.submitButton);
		submitButton.setOnClickListener(this::getLogFromStopWatch);
		Button configButton = findViewById(R.id.configButton);
		configButton.setOnClickListener(v -> {
			int selectId = radioGroup.getCheckedRadioButtonId();
			for (RadioButton radioButton : mRadioButtonList) {
				if (selectId == radioButton.getId()) {
					int level = (int) radioButton.getTag();
					setLogLevelFromStopWatch(level);
					break;
				}
			}
		});
		switchCompat.setOnCheckedChangeListener((v, isChecked) -> {
			PreferenceUtil.put(StopWatchLogActivity.this, KEY_STOP_WATCH_LOG, isChecked);
			radioGroup.setEnabled(isChecked);
			radioButton1.setEnabled(isChecked);
			radioButton2.setEnabled(isChecked);
			radioButton3.setEnabled(isChecked);
			radioButton4.setEnabled(isChecked);
			radioButton5.setEnabled(isChecked);
			radioButton6.setEnabled(isChecked);
			radioButton7.setEnabled(isChecked);
			submitButton.setEnabled(isChecked);
			configButton.setEnabled(isChecked);
			if (isChecked) {
				switchCompat.setText(R.string.setting_stop_watch_log_off);
			} else {
				switchCompat.setText(R.string.setting_stop_watch_log_on);
			}
		});
		getLogLevelFromStopWatch();
	}

	@Override protected void setInstance() {

	}

	@Override protected void removeInstance() {

	}

	private void getLogFromStopWatch(View view) {
		if (mPresenter != null) {
			showLoadingDialog();
			mPresenter.setProtocolServiceListener(StopWatchLogActivity.this);
			mPresenter.setProtocolBBServiceListener(StopWatchLogActivity.this);
			mPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_GET_BB_OFFLINE_CONFIG_LIST, "", "");
		}
		//String fileName = FileUtils.checkExternalDirectoryPathExist(true, SettingsJsonUtils.getDeviceModel(this), SettingsJsonUtils.getSn(this), SettingsJsonUtils.DEVICE_LOG, "log_nan_20250326164005.zip");
		//uploadLog(fileName);
	}

	private void getLogLevelFromStopWatch() {
		if (mPresenter != null) {
			showLoadingDialog();
			mPresenter.setProtocolServiceListener(StopWatchLogActivity.this);
			mPresenter.setProtocolBBServiceListener(StopWatchLogActivity.this);
			mPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_GET_BB_OFFLINE_LOG_LEVEL_INFO, "", "");
		}
	}

	private void setLogLevelFromStopWatch(int level) {
		if (mPresenter != null) {
			showLoadingDialog();
			mPresenter.setProtocolServiceListener(StopWatchLogActivity.this);
			mPresenter.setProtocolBBServiceListener(StopWatchLogActivity.this);
			mPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_SET_BB_OFFLINE_LOG_LEVEL_INFO, "", "", String.valueOf(level));
		}
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {

	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {

	}

	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
		Log.i("StopWatchLogActivity onStateChangedMessage msg:" + msg + ",msgStr:" + msgStr);
		if (BesSdkConstants.BES_CONNECT_ERROR == msg) {
			runOnUiThread(() -> showToast(msgStr));
			Intent intent = new Intent(this, XZDeviceListActivity.class);
			startActivity(intent);
			finish();
		}
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {
		if (Constants.DEVICE_LOG_SET_LEVEL_SUCCESS == msg) {
			runOnUiThread(() -> {
				dismissLoadingDialog();
				ToastUtils.showShort(R.string.setting_success);
			});
		}
	}

	private void showLoadingDialog() {
		if (mCircularProgressDialog == null) {
			mCircularProgressDialog = new CircularProgressDialog(this, true, false, null);
		}

		mCircularProgressDialog.show(R.string.dialog_loading);
	}

	private void dismissLoadingDialog() {
		if (mCircularProgressDialog != null) {
			mCircularProgressDialog.dismiss();
			mCircularProgressDialog = null;
		}
	}

	@Override public void onBBSMessage(int msg, String params) {
		Log.i("StopWatchLogActivity onBBSMessage msg = " + msg + ",params = " + params);
		if (Constants.DEVICE_LOG_GET_LEVEL_SUCCESS == msg) {
			runOnUiThread(() -> {
				dismissLoadingDialog();
				int level = Integer.parseInt(params);
				setLogLevel(level);
			});
		} else if (Constants.DEVICE_GET_LOG_SUCCESS == msg) {
			uploadLog(params);
		}
	}

	private void setLogLevel(int level) {
		for (RadioButton radioButton : mRadioButtonList) {
			int tag = (int) radioButton.getTag();
			if (tag == level) {
				radioButton.setChecked(true);
				break;
			}
		}
	}

	private void uploadLog(String fileName) {
		Observable.create(new NetSubscribe(MyHttpClient.uploadLog(Constants.TYPE_STOP_WATCH_LOG, fileName, "", App.getContext().getUserPhone()))).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
			@Override public void onCompleted() {
				dismissLoadingDialog();
			}

			@Override public void onError(Throwable th) {
				ToastUtils.showShort(R.string.toast_upload_failed);
				dismissLoadingDialog();
			}

			@Override public void onNext(String str) {
				if (!TextUtils.isEmpty(str)) {
					try {
						JSONObject jsonObject = new JSONObject(str);
						int code = jsonObject.optInt("code");
						if (200 == code) {
							FileUtils.deleteFile(fileName);
							ToastUtils.showShort(R.string.toast_upload_successful);
						} else {
							ToastUtils.showShort(R.string.toast_upload_failed);
						}
					} catch (JSONException e) {
						throw new RuntimeException(e);
					}
				} else {
					ToastUtils.showShort(R.string.toast_upload_failed);
				}
			}
		});
	}
}